package cn.dapeng.base;

import cn.dapeng.util.SleepingUtil;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;


/**
 *
 *  interrupt对ReentrantLock的lockInterruptibly方法有影响，会触发异常
 *
 */
public class LockInterruptiblyAndInterreupt {

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            lock.lock();
            try {
                SleepingUtil.sleep(5, TimeUnit.SECONDS);
            } finally {
                lock.unlock();
            }

            System.out.println("t1 end");
        });

        t1.start();

        SleepingUtil.sleep(1, TimeUnit.SECONDS);

        Thread t2 = new Thread(() -> {
            try {
                try {
                    lock.lockInterruptibly();
                } catch (InterruptedException e) {
                    System.out.println("t2 interrupted");
                    System.out.println(Thread.currentThread().isInterrupted());
                }
            } finally {
                if(lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }

            System.out.println("t2 end");
        });

        SleepingUtil.sleep(1, TimeUnit.SECONDS);

        t2.start();

        t2.interrupt();

    }
}
